import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Form, Upload, Icon, Modal, message } from 'antd';
import styles from '../../../index.less';
import * as config from '../../../utils/config';

const FormItem = Form.Item;
const { Dragger } = Upload;

class TabPicComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
      app: props.app,
      sActiveId: props.sActiveId,
      disabled: props.disabled,
      savePathStr: '', /* 回带的图片地址 */
    };
  }

  componentWillReceiveProps(nextProps) {
    const { disabled, dataSet } = nextProps;
    if (Object.keys(dataSet).length > 0
      && this.state.fileList.length === 0
      && (dataSet.sPicturePath !== undefined && dataSet.sPicturePath !== '')) {
      const { sActiveId } = this.state;
      const { token } = this.state.app;
      const savePathStr = dataSet.sPicturePath;
      const url = `${config.server_host}file/download?sModelsId=${sActiveId}&token=${token}&savePathStr=${savePathStr}`;
      const fileList = [{
        uid: dataSet.sId,
        name: '',
        status: 'done',
        url,
        thumbUrl: url,
      }];
      this.setState({ fileList, savePathStr });
    }
    this.setState({ disabled });
  }

  handleChange = (info) => {
    /* 替换原来上传的图片 */
    let { fileList } = info;
    fileList = fileList.slice(-1);
    let savePathStr = '';
    fileList = fileList.map((file) => {
      if (file.response) {
        savePathStr = { ...file.response.dataset.rows[0].savePathStr };
        const { sActiveId } = this.state;
        const { token } = this.state.app;
        const url = `${config.server_host}file/download?sModelsId=${sActiveId}&token=${token}&savePathStr=${savePathStr}`;
        file.url = url;
      }
      return file;
    });
    this.setState({ fileList, savePathStr });
    if (Object.keys(savePathStr).length > 0) {
      this.props.onPicturePath(savePathStr);
    }
  };

  handleCancel = () => {
    this.setState({ previewVisible: false });
  };

  handleRemove = () => {
    /* 查看时不可删除 */
    const { disabled } = this.state;
    if (disabled) return false;
    const { sActiveId, savePathStr } = this.state;
    const { token } = this.state.app;
    const value = { savePathStr };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    const url = `${config.server_host}file/remove?sModelsId=${sActiveId}`;
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        message.success(json.msg);
        this.setState({
          savePathStr: '',
          fileList: [],
        });
        this.props.onPicturePath('');
      } else {
        message.error(json.msg);
        return false;
      }
    });
  };

  handlePreview = (file) => {
    /* 点击放大预览 */
    const { disabled } = this.state;
    if (disabled) return;
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const { app, sActiveId, disabled } = this.state;
    const { token } = app;
    const data = {
      name: 'file',
      action: `${config.server_host}file/upload?sModelsId=${sActiveId}&token=${token}`,
      listType: 'picture',
      className: `${styles.uploadListInline}`,
      fileList,
      onChange: this.handleChange,
      accept: 'image/*',
      beforeUpload: () => {
        /* 查看时不可上传 */
        if (disabled) return false;
      },
    };
    return (
      <FormItem className={styles.searchForm} style={{ paddingLeft: 20, paddingRight: 20 }}>
        <Dragger
          {...data}
          onPreview={this.handlePreview}
          onRemove={this.handleRemove}
        >
          <p className="ant-upload-drag-icon">
            <Icon type="inbox" />
          </p>
          <p className="ant-upload-text">点击或拖动文件以此区域上传</p>
          <p className="ant-upload-hint">只接受上传图片文件</p>
        </Dragger>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
          width="800"
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </FormItem>
    );
  }
}

export default TabPicComponent;
